package tw.com.hitevision.whiteboard.android.widgets.floatView.widget.appfloat

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.MotionEvent
import android.widget.FrameLayout
import tw.com.hitevision.whiteboard.android.Props
import tw.com.hitevision.whiteboard.android.widgets.floatView.data.FloatConfig
import tw.com.hitevision.whiteboard.android.widgets.floatView.interfaces.OnFloatTouchListener
import tw.com.hitevision.whiteboard.android.widgets.floatView.utils.InputMethodUtils

@SuppressLint("ViewConstructor")
internal class ParentFrameLayout(
        context: Context,
        private val config: FloatConfig,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    var touchListener: OnFloatTouchListener? = null
    var layoutListener: OnLayoutListener? = null
    private var isCreated = false

    interface OnLayoutListener {
        fun onLayout()
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        if (!isCreated) {
            if(Props.isFake4k()) { changeDPI(3f) }
            isCreated = true
            layoutListener?.onLayout()
        }
    }

    override fun onInterceptTouchEvent(event: MotionEvent?): Boolean {
        if (event != null) touchListener?.onTouch(event)
        return config.isDrag || super.onInterceptTouchEvent(event)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event != null) touchListener?.onTouch(event)
        return config.isDrag || super.onTouchEvent(event)
    }

    override fun dispatchKeyEventPreIme(event: KeyEvent?): Boolean {
        if (config.hasEditText && event?.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_BACK) {
            InputMethodUtils.closedInputMethod(FloatManager.getTag(config.floatTag))
        }
        return super.dispatchKeyEventPreIme(event)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        config.callbacks?.dismiss()
        config.floatCallbacks?.builder?.dismiss?.invoke()
    }

    private fun changeDPI(newDpi: Float) {
        val metrics = resources.displayMetrics
        if (newDpi != metrics.density) {
            val scale = metrics.density / newDpi
            metrics.density /= scale
            metrics.scaledDensity /= scale
            metrics.densityDpi = (metrics.densityDpi / scale).toInt()
            metrics.xdpi /= scale
            metrics.ydpi /= scale
            resources.displayMetrics.setTo(metrics)
        }
    }
}